package com.sxhuayuan.parking.controller.open;

import java.util.Set;

import javax.annotation.Resource;
import javax.validation.ConstraintViolation;
import javax.validation.Validator;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import com.sxhuayuan.parking.utils.SpringUtils;

public class BaseController {

	Logger log = LoggerFactory.getLogger(BaseController.class);

	@Resource(name = "validator")
	private Validator validator;

	/** "验证结果"参数名称 */
	private static final String CONSTRAINT_VIOLATIONS_ATTRIBUTE_NAME = "constraintViolations";

	/**
	 * 数据验证
	 * 
	 * @param target
	 *            验证对象
	 * @param groups
	 *            验证组
	 * @return 验证结果
	 */
	protected boolean isValid(Object target, Class<?>... groups) {
		Set<ConstraintViolation<Object>> constraintViolations = validator.validate(target, groups);
		if (constraintViolations.isEmpty()) {
			return true;
		} else {
			RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
			requestAttributes.setAttribute(CONSTRAINT_VIOLATIONS_ATTRIBUTE_NAME, constraintViolations, RequestAttributes.SCOPE_REQUEST);
			return false;
		}
	}

	@SuppressWarnings("unchecked")
	protected Set<ConstraintViolation<Object>> getValidInfo() {
		RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
		return (Set<ConstraintViolation<Object>>) requestAttributes.getAttribute(CONSTRAINT_VIOLATIONS_ATTRIBUTE_NAME, RequestAttributes.SCOPE_REQUEST);
	}

	public ApiResp getValidErrorInfo() {
		StringBuilder info = new StringBuilder();
		for (ConstraintViolation<Object> c : getValidInfo()) {
			info.append(c.getPropertyPath()).append(SpringUtils.getMessage(c.getMessage())).append("; ");
		}
		return ApiResp.error("params is invalid: " + info.toString());
	}

	/**
	 * @Title: operateExp
	 * @Description: 统一异常处理
	 * @param ex
	 * @param request
	 * @return String
	 */
	// @ExceptionHandler(RuntimeException.class)
	// public ApiResp operateExp(RuntimeException ex, HttpServletRequest request) {
	// log.error("操作失败：" + ex.getMessage());
	// Object token = request.getSession().getAttribute("sign_token");
	// log.debug("token in session = {}", token);
	// return ApiResp.error(ex.getMessage()).sign(String.valueOf(token));
	// }
}
